package top.infopub.mgr.cap.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.dto.mkt.LoanContractDto;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.mgr.cap.dao.FinancialInstitutionsDao;
import top.infopub.mgr.cap.dao.LoanContractDao;
import top.infopub.mgr.cap.domain.DropLoanFinDomain;
import top.infopub.mgr.cap.service.LoanContractService;
import top.infopub.mgr.cap.vo.RepaymentScheduleInfoVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.mkt.dao.ProjectAttachmentDao;
import top.infopub.mgr.mkt.service.impl.CollectProjectServiceImpl;
import top.infopub.model.cap.*;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author Warking
 * @Date 2021/5/24 9:39
 * @Version 1.0 借款合同
 */
@Service
public class LoanContractServiceImpl extends GenericFlowController implements LoanContractService{

    @Autowired
    private LoanContractDao loanContractDao;
    @Autowired
    private CollectProjectServiceImpl collectProjectService;
    @Autowired
    private ProjectAttachmentDao projectAttachmentDao;
    @Autowired
    private FinancialInstitutionsDao financialInstitutionsDao;

    /*借款合同列表接口*/
    @Override
    public Page<LoanContract> selectPage(Page<LoanContract> page, LoanContract loanContract) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return loanContractDao.selectPage(loanContract);
    }

    /*借款合同详情*/
    @Override
    public LoanContractDto queryDetail(String id) {
        List<LoanContractDetail> detailList = new ArrayList<>();
        LoanContractDto dto = new LoanContractDto();
        //查询主表数据
        LoanContract loanContract = loanContractDao.findById(id);
        //根据主表ID查询子表数据
        List<LoanContractSublist> sublistList = loanContractDao.selectSublistById(id);
        for (LoanContractSublist loan : sublistList) {
            LoanContractDetail detail = new LoanContractDetail();
            //根据子表金融ID去查询金融机构的数据
            SetupFinancial setupFinancial = loanContractDao.findBySublistId(loan.getSetupFinancialId(),loanContract.getId());
            detail.setSetupFinancial(setupFinancial);
            detail.setLoanContractSublist(loan);
            detailList.add(detail);
        }
        dto.setLoanContract(loanContract);
        dto.setLoanContractDetailList(detailList);
        //附件信息
        //附件查询
        //附件信息表
        List<ProjectAttachment> projectAttaList = projectAttachmentDao.queryByWhere(loanContract.getProCode(), ProjectFileTypeEnum.FILE_TYPE48.getCode(), null);
        loanContract.setFileAtt(collectProjectService.fileAttaListToArray(projectAttaList));
        return dto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String save(LoanContractDto dto, String proCode) {
        LoanContract loanContract = dto.getLoanContract();
        List<LoanContractDetail> loanContractDetailList = dto.getLoanContractDetailList();
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        if (loanContract != null) {        //根据ID判断是新增还是修改
            if (StringUtils.isEmpty(loanContract.getId())) {
              String flag =  loanContractDao.selectByProCodeFlag(dto.getLoanContract().getProCode());
              if ("true".equals(flag))
              {
                  //已经有重复是项目了
                  return  flag;
              }
                //保存
                loanContract.setAddBy(vo.getId());
                loanContract.setAddTime(new Date());
                loanContractDao.saveLoanContract(loanContract);
                //保存子表数据
                for (LoanContractDetail loanContractDetail : loanContractDetailList) {
                    LoanContractSublist sublist = loanContractDetail.getLoanContractSublist();
                    sublist.setAddBy(vo.getId());
                    sublist.setAddTime(new Date());
                    /*主表ID*/
                    String id = loanContract.getId();
                    sublist.setLoanContractId(id);
                    loanContractDao.saveLoanContractSublist(sublist);
                }
            } else {
                //修改
                loanContract.setUptBy(vo.getId());
                loanContract.setUptTime(new Date());
                loanContractDao.updateLoanContract(loanContract);
                //保存子表数据
                for (LoanContractDetail loanContractDetail : loanContractDetailList) {
                    LoanContractSublist sublist = loanContractDetail.getLoanContractSublist();
                    sublist.setUptBy(vo.getId());
                    sublist.setUptTime(new Date());
                    loanContractDao.updateLoanContractSublist(sublist);
                }
            }
            //附件保存
            //前端附件信息
            //更新附件表-MKT_PROJECT_ATTACHMENT
            List<ProjectAttachment> attachmentList = new ArrayList<>();
            if (loanContract.getFileAtt() != null) {
                String[] fileAtt = loanContract.getFileAtt();
                for (String file : fileAtt) {
                    ProjectAttachment attachment = createProjectFileAtta(vo, proCode, file);
                    attachmentList.add(attachment);
                }
            }
            //更新附件信息
            projectAttachmentDao.deleteByWhere(proCode, ProjectFileTypeEnum.FILE_TYPE48.getCode(), null);
            if (attachmentList != null && attachmentList.size() > 0) {
                projectAttachmentDao.insertBatch(attachmentList);
            }
            return loanContract.getId();
        } else {
            return null;
        }

    }

    /*根据主表查询数据*/
    @Override
    public LoanContract findById(String id) {
        return   loanContractDao.findById(id);
    }
    /*项目下拉接口  从金融机构选择 查询*/
    @Override
    public List<Map<String,String>> selectProCode() {
        return loanContractDao.selectProCode();
    }

    @Override
    public List<SetupFinancial> selectOrganization(String id) {
        /*根据ID查询立项金融的数据*/
        ArrayList<SetupFinancial> list = new ArrayList<>();
        //根据主表ID查询子表数据
        List<FinancialElectSublist> financialElectSublistList = financialInstitutionsDao.selectSublistById(id);
        for (FinancialElectSublist sublist : financialElectSublistList) {
            //根据子表的金融ID 查询详情数据
            SetupFinancial setupFinancial = financialInstitutionsDao.selectByIdSetupFinancial(sublist.getSetupFinancialId());
            //设置拟题用金额
            setupFinancial.setAmountCreditExtension(sublist.getAmountCreditExtension());
            list.add(setupFinancial);
        }
        return list;
    }

    @Override
    public List<DropLoanFinDomain> selectProject() {

        return loanContractDao.selectProject();
    }

    @Override
    public List<RepaymentScheduleInfoVo> selectDockById(String id) {
        return loanContractDao.selectDockById(id);
    }
}
